package top.whysu.gps.utils;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.RuntimeUtil;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import top.whysu.gps.constant.CodeConstant;
import top.whysu.gps.constant.NetConstant;
import top.whysu.gps.dto.system.WriteProperty;
import top.whysu.gps.exception.BusinessException;

import java.io.*;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.CRC32;


/**
 * 公共工具类
 */
public class CommonUtil {

    private static final Logger LOGGER = LoggerFactory.getLogger(CommonUtil.class);

    /**
     * 将po对象的属性值赋值给dto对象相同属性名的属性
     * 此方法能将第一个转第二个无论是否DTO
     *
     * @param po  赋值的对象
     * @param dto 被赋值的对象
     * @return
     * @throws Exception
     */
    public static Object poToDto(Object po, Object dto) throws Exception {
        Class poClass = po.getClass();
        Class dtoClass = dto.getClass();
        // 取得po对象的所有属性
        Field[] poFields = poClass.getDeclaredFields();
        //取父类的所有属性
        Field[] superPoFields = poClass.getSuperclass().getDeclaredFields();
        //合并数组
        poFields = (Field[]) mergeArray(poFields, superPoFields);

        // 遍历拼接dto的set方法字段表示
        for (Field f : poFields) {
            String fieldName = f.getName();
            //取得当前get，set字符串表达形式
            String dtoSetMethodName = "set" + firstToBig(fieldName);
            String poGetMethodName = "get" + firstToBig(fieldName);

            //System.out.println(fieldName + "=====" + dtoSetMethodName);
            // 取得DTO对象的set方法
            Method dtoSetMethod = null;
            try {
                dtoSetMethod = dtoClass.getMethod(dtoSetMethodName, f.getType());
            } catch (NoSuchMethodException e) {//如果不存在此方法跳过，
                continue;
            }
            //取得Po对象的get方法
            Method poGetMethod = poClass.getMethod(poGetMethodName, null);
            // 将po对象的属性值set到dto对象中去
            dtoSetMethod.invoke(dto, poGetMethod.invoke(po, null));
        }
        return dto;

    }

    /**
     * 合并数组
     *
     * @param a
     * @param b
     * @return
     */
    public static Object[] mergeArray(Object[] a, Object[] b) {
        Object[] c = Arrays.copyOf(a, a.length + b.length);
        System.arraycopy(b, 0, c, a.length, b.length);
        return c;
    }

    /**
     * 首字母大写
     *
     * @param fieldName
     * @return
     */
    public static String firstToBig(String fieldName) {
        if (fieldName != null && fieldName != "") {
            fieldName = fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);
        }
        return fieldName;
    }

    /**
     * 生成唯一码 17位时间戳+3位随机码
     *
     * @return
     */
    public static String generateUnique() {
        return StringUtils.join(DateFormatUtils.format(Calendar.getInstance().getTime(), "yyyyMMddHHmmssSSS"),
                RandomStringUtils.randomNumeric(3));
    }

    /**
     * 是否空列表
     *
     * @param collection
     * @return
     */
    public static boolean isEmptyOfCollection(Collection<?> collection) {
        return collection == null || collection.size() <= 0;
    }

    /**
     * 获取本机mac地址
     */
    public static String getLocalMac() {
        String mac = null;
        byte[] macBytes = null;
        try {
            InetAddress ia = InetAddress.getLocalHost();
            macBytes = NetworkInterface.getByInetAddress(ia).getHardwareAddress();
        } catch (UnknownHostException | SocketException e) {
            e.printStackTrace();
        }
        // 非断网情况，断网情况配置了mac地址（绕过加密狗校验），登陆会报错“您的帐号已在另一处登陆”
        if (macBytes != null) {
            StringBuffer sb = new StringBuffer();
            for (int i = 0; i < macBytes.length; i++) {
                if (i != 0) {
                    sb.append("-");
                }
                String s = Integer.toHexString(macBytes[i] & 0xFF);
                sb.append(s.length() == 1 ? 0 + s : s);
                mac = sb.toString().toUpperCase();
            }
        }
        return mac;
    }

    /**
     * 文件CRC32校验
     *
     * @param filePath
     * @return
     */
    public static String getCRC32(String filePath) {
        String result = "";
        try {
            CRC32 crc32 = new CRC32();
            crc32.update(FileUtil.readBytes(filePath));
            result = crc32.getValue() + "";
        } catch (Exception e) {
            LOGGER.error("crc32检验异常：", e);
        }
        return result;
    }


    public static <T> void removeListItem(List<T> list, T item) {
        list.removeIf(nextItem -> nextItem == item);
    }

    /**
     * 创建以零开头字符串
     *
     * @param digits   字符串位数
     * @param original 原字符串
     * @return
     */
    public static String createStartWithZero(int digits, String original) {
        String result = "";

        for (int i = 0; i < digits - original.length(); i++) {
            result += "0";
        }

        result += original;

        return result;

    }

    /**
     * 获取网络信息
     *
     * @return 网络信息
     */
    public static WriteProperty getNetWorkInfo() {
        WriteProperty writeProperty = new WriteProperty();
        // 网关地址
        String gateway = null;
        // 子网掩码
        String mask = null;
        // 内网IP
        String localIp = null;
        //  DNS地址
        String dns = "114.114.114.114";
        // 获取系统名称
        String osName = System.getProperty(NetConstant.OS_NAME);
        try {
            if (osName.toLowerCase().contains(NetConstant.LINUX_OS)) {
                // LINUX下
                // 网关信息
                String gatewayInfo = RuntimeUtil.execForStr(NetConstant.IP_ROUTE_SHOW);
                LOGGER.info("网关信息->{}", gatewayInfo);
                int viaIndex = gatewayInfo.indexOf(NetConstant.DEFAULT_VIA);
                // 网卡名称
                String netCardName = null;
                if (-1 != viaIndex) {
                    String viaString = gatewayInfo.substring(viaIndex,
                            gatewayInfo.length());
                    String[] viaArry = viaString.split(" ");
                    gateway = viaArry[2];
                    netCardName = viaArry[4];
                }
                // 子网掩码
                String maskCmd;
                if (StringUtils.isNotBlank(netCardName)) {
                    maskCmd = NetConstant.IFCONFIG + " " + netCardName;
                } else {
                    maskCmd = NetConstant.IFCONFIG;
                }
                String maskInfo = RuntimeUtil.execForStr(maskCmd);
                LOGGER.info("子网掩码信息->{}", maskInfo);
                int maskIndex = maskInfo.indexOf(NetConstant.MASK);
                if (-1 != maskIndex) {
                    String maskAll = maskInfo.substring(maskIndex + 8, maskInfo.length() - 1);
                    String[] maskArry = maskAll.split(" ");
                    mask = maskArry[0];
                }
                // 内网IP
                int ipIndex = maskInfo.indexOf(NetConstant.IP);
                if (-1 != ipIndex) {
                    String ipAll = maskInfo.substring(ipIndex + 5, maskInfo.length() - 1);
                    String[] ipArry = ipAll.split(" ");
                    localIp = ipArry[0];
                }
                // 获取DNS
                String dnsInfo = RuntimeUtil.execForStr(NetConstant.DNS_SHOW);
                LOGGER.info("DNS信息->{}", dnsInfo);
                if (StringUtils.isNotBlank(dnsInfo)) {
                    // DNS服务器 默认获取第一个
                    Matcher dnsMc = Pattern.compile("\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}").matcher(dnsInfo);
                    if (dnsMc.find()) {
                        dns = dnsMc.group();
                    }
                }
            } else if (osName.toLowerCase().contains(NetConstant.WINDOWS_OS)) {
                // WINDOWS下
                Process pro = Runtime.getRuntime().exec(NetConstant.IPCONFIG_ALL);
                BufferedReader br = new BufferedReader(new InputStreamReader(pro.getInputStream(), "gbk"));
                List<String> rowList = new ArrayList<>();
                String temp;
                while ((temp = br.readLine()) != null) {
                    rowList.add(temp);
                }
                for (String row : rowList) {
                    String maskString = "子网掩码";
                    String gatwayString = "默认网关";
                    String dnsString = "DNS 服务器";
                    String ipString = "IPv4 地址";
                    if (row.contains(maskString)) {
                        // 子网掩码
                        Matcher maskMc = Pattern.compile("\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}").matcher(row);
                        if (maskMc.find()) {
                            mask = maskMc.group();
                        }
                    }
                    if (row.contains(gatwayString)) {
                        // 网关地址
                        Matcher gatwayMc = Pattern.compile("\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}").matcher(row);
                        if (gatwayMc.find()) {
                            gateway = gatwayMc.group();
                        }
                    }
                    if (row.contains(dnsString)) {
                        // DNS服务器
                        Matcher dnsMc = Pattern.compile("\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}").matcher(row);
                        if (dnsMc.find()) {
                            dns = dnsMc.group();
                        }
                    }
                    if (row.contains(ipString)) {
                        // IP地址
                        Matcher ip = Pattern.compile("\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}").matcher(row);
                        if (ip.find()) {
                            // 如果找到了localIp就不再往下找了
                            if (StringUtils.isBlank(localIp)) {
                                localIp = ip.group();
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            LOGGER.error("获取网络信息EXCEPTION->", e);
        }
        LOGGER.info("网络信息->网关地址：{}->子网掩码：{}->" + "DNS：{}",
                new Object[]{gateway, mask, dns});
        writeProperty.setGatewayIp(gateway);
        writeProperty.setSubNetMask(mask);
        writeProperty.setDns(dns);
        writeProperty.setLocalIp(localIp);
        return writeProperty;
    }

    /**
     * 设置Linux系统网络配置(默认网卡名eth0)
     * IPADDR=192.168.156.80 - - >这是你自己设置的IP地址，必须符合规则
     * GATEWAY=192.168.156.2 - - >这是网关地址
     * NETMASK=255.255.255.0 - - >这是子网掩码
     * DNS1=192.168.156.2 - - >写成网关地址
     *
     * @param ipaddr
     * @param gateway
     * @param netmask
     * @param dns1
     */
    public static void setNetwork(String ipaddr, String gateway, String netmask, String dns1) {
        //获取操作系统名称
        LOGGER.info("设置网络参数开始===================>");
        String os = System.getProperty("os.name");
        // 获取默认网卡名称
        os = os.toUpperCase();
        if (os.startsWith("LINUX")) {
            String gatewayInfo = RuntimeUtil.execForStr(NetConstant.IP_ROUTE_SHOW);
            LOGGER.info("当前网关信息->{}", gatewayInfo);
            int viaIndex = gatewayInfo.indexOf(NetConstant.DEFAULT_VIA);
            String netCardName = "em1";
            if (-1 != viaIndex) {
                netCardName = gatewayInfo.substring(viaIndex,
                        gatewayInfo.length()).split(" ")[4];
            }
            Map<String, String> beforeMap = new LinkedHashMap<>(8);
            String path = "/etc/sysconfig/network-scripts/ifcfg-" + netCardName;
            try {
                FileInputStream fis = new FileInputStream(path);
                InputStreamReader isr = new InputStreamReader(fis, "UTF-8");
                BufferedReader br = new BufferedReader(isr);
                String lineStr;
                // 按行读取字符串
                while ((lineStr = br.readLine()) != null) {
                    String[] infos = lineStr.split("=");
                    beforeMap.put(infos[0], infos[1]);
                }
                br.close();
                isr.close();
                fis.close();
                LOGGER.info("系统参数修改前-> IP：{}，NETMASK：{}，GATEWAY：{}，DNS1:{}",
                        new Object[]{beforeMap.get("IPADDR"), beforeMap.get("NETMASK"), beforeMap.get("GATEWAY"), beforeMap.get("DNS1")});
                //修改网络配置参数
                beforeMap.put("BOOTPROTO", "static");
                beforeMap.put("ONBOOT", "yes");
                if (StringUtils.isNotBlank(ipaddr)) {
                    beforeMap.put("IPADDR", ipaddr);
                }
                if (StringUtils.isNotBlank(gateway)) {
                    beforeMap.put("GATEWAY", gateway);
                }
                if (StringUtils.isNotBlank(netmask)) {
                    beforeMap.put("NETMASK", netmask);
                }
                if (StringUtils.isNotBlank(dns1)) {
                    beforeMap.put("DNS1", dns1);
                }
                //按行写入字符串
                FileOutputStream fos = new FileOutputStream(new File(path));
                OutputStreamWriter osw = new OutputStreamWriter(fos, "UTF-8");
                BufferedWriter bw = new BufferedWriter(osw);
                for (Map.Entry<String, String> entry : beforeMap.entrySet()) {
                    bw.write(entry.getKey() + "=" + entry.getValue());
                    bw.newLine();
                }
                bw.flush();
                bw.close();
                osw.close();
                fos.close();

                // 对比一下修改前后数据是否一致
                FileInputStream af = new FileInputStream(path);
                InputStreamReader afr = new InputStreamReader(af, "UTF-8");
                BufferedReader afbr = new BufferedReader(afr);
                Map<String, Object> modifyMap = new HashMap<>(1);
                while ((lineStr = afbr.readLine()) != null) {
                    String[] infos = lineStr.split("=");
                    modifyMap.put(infos[0], infos[1]);
                }
                LOGGER.info("：系统参数修改后-> IP：{}，NETMASK：{}，GATEWAY：{}，DNS1:{}",
                        new Object[]{modifyMap.get("IPADDR"), modifyMap.get("NETMASK"), modifyMap.get("GATEWAY"), modifyMap.get("DNS1")});
                LOGGER.info("设置网络参数结束===============>");

                // 比较是否修改成功
                if (!compareSystemConfig(modifyMap, ipaddr, gateway, netmask, dns1)) {
                    // 修改失败，提示前端，重新修改
                    throw new BusinessException(CodeConstant.Http.PARAM_ERROR, "设置网络参数失败，请重试！");
                }

                // 重启系统
                LOGGER.info("修改服务器参数成功，开始重启系统！！！");
                Runtime run = Runtime.getRuntime();
                run.exec("systemctl restart network");
            } catch (IOException e) {
                LOGGER.error("设置系统网络配置EXCEPTION->", e);
                throw new BusinessException(CodeConstant.Http.PARAM_ERROR, "设置网络参数失败，请重试！");
            }
        }
    }

    /**
     * @description: 比较修改前后是否有变化
     * @author: guoyuxuan@2019/10/17 10:11
     * @param: [afterMap 修改后的配置, ipaddr, gateway, netmask, dns1]
     * @return: boolean false修改失败；true 修改成功；
     * @throws:
     */
    private static boolean compareSystemConfig(Map<String, Object> afterMap, String ipaddr, String gateway, String netmask, String dns1) {
        return afterMap != null && (ipaddr.equals(afterMap.get("IPADDR"))
                || gateway.equals(afterMap.get("GATEWAY"))
                || netmask.equals(afterMap.get("NETMASK"))
                || dns1.equals(afterMap.get("DNS1")));
    }

    /**
     * @description: 获取sed替换匹配行命令
     * @author: guoyuxuan@2019/8/5 16:06
     * @param: [key 参数名, value 参数对应的内容, filePath 文件路径]
     * @return: java.lang.String
     * @throws:
     */
    private static String getSedStr(String key, String value, String filePath) {
        String content = key + "=" + value;
        return "sed -i 's/^" + key + "=.*/" + content + "/g' " + filePath;
    }


    /**
     * 判断两个IP是否处于同一个子网
     *
     * @param ip1  IP1
     * @param ip2  IP2
     * @param mask 子网掩码
     * @return 是否同一个子网 true同网，false不同网
     */

    public static boolean checkOnSubnet(String ip1, String ip2, String mask) {
        boolean isOneNet = true;
        String[] ip1Arry = ip1.split("\\.");
        String[] ip2Arry = ip2.split("\\.");
        String[] maskArry = mask.split("\\.");

        for (int i = 0; i < maskArry.length; i++) {
            if ((Integer.valueOf(maskArry[i]) & Integer.valueOf(ip1Arry[i]))
                    != (Integer.valueOf(maskArry[i]) & Integer.valueOf(ip2Arry[i]))) {
                isOneNet = false;
                break;
            }
        }

        return isOneNet;
    }

    /**
     * 获取CPU序列号
     *
     * @return
     */
    public static String getProcessorId() {
        Process process = null;
        try {
            process = Runtime.getRuntime().exec(new String[]{"wmic", "cpu", "get", "ProcessorId"});
            process.getOutputStream().close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        Scanner sc = new Scanner(process.getInputStream());
        String property = sc.next();
        String serial = sc.next();
        return serial;
    }


    /**
     * 执行命令
     *
     * @param cmd
     * @return
     */
    public static String executeCmd(String cmd) {
        try {
            System.out.println("got cmd job : " + cmd);
            Runtime run = Runtime.getRuntime();
            Process process;
            process = run.exec(cmd);
            InputStream in = process.getInputStream();
            StringBuffer out = new StringBuffer();
            byte[] b = new byte[8192];
            for (int n; (n = in.read(b)) != -1; ) {
                out.append(new String(b, 0, n));
            }
            in.close();
            process.destroy();
            return out.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 执行命令完,结果处理
     *
     * @param cmd    命令语句
     * @param record 要查看的字段
     * @param symbol 分隔符
     * @return
     */
    public static String getSerialNumber(String cmd, String record, String symbol) {
        String execResult = executeCmd(cmd);
        String[] infos = execResult.split("\n");
        for (String info : infos) {
            info = info.trim();
            if (info.indexOf(record) != -1) {
                info.replace(" ", "");
                String[] sn = info.split(symbol);
                return sn[1].replace(" ", "");
            }
        }
        return null;
    }

    /**
     * 获取当前系统cpu序列号
     *
     * @return
     */
    public static String getCurSystemCPU() {
        //获取操作系统名称
        String os = System.getProperty("os.name");
        os = os.toUpperCase();
        if (os.startsWith("LINUX")) {
            return getSerialNumber("dmidecode -t processor | grep 'ID'", "ID", ":");
        } else if (os.startsWith("WINDOWS")) {
            String execResult = executeCmd("wmic cpu get ProcessorId");
            String[] infos = execResult.split("\n");
            if (null != infos && infos.length >= 1) {
                return infos[1].trim();
            }
        }
        return null;
    }

    /**
     * 获取硬盘序列号
     *
     * @return
     */
    public static String getCurSystemHardDisk() {
        //获取操作系统名称
        String os = System.getProperty("os.name");
        os = os.toUpperCase();
        if (os.startsWith("LINUX")) {
            return getSerialNumber("fdisk -l", "Disk identifier", ":");
        } else if (os.startsWith("WINDOWS")) {
            String execResult = executeCmd("wmic diskdrive get serialnumber");
            String[] infos = execResult.split("\n");
            if (null != infos && infos.length >= 1) {
                return infos[1].trim();
            }
        }
        return null;
    }

    /**
     * 获取当前系统MAC地址
     *
     * @return
     */
    public static String getCurSystemMAC() {
        //获取操作系统名称
        String os = System.getProperty("os.name");
        os = os.toUpperCase();
        if (os.startsWith("LINUX")) {
            return getSerialNumber("ifconfig -a", "ether", " ");
        } else if (os.startsWith("WINDOWS")) {
            return getLocalMac();
        }
        return null;
    }

    /**
     * 获取当前系统主板序列号
     *
     * @return
     */
    public static String getCurSystemBaseBoard() {
        //获取操作系统名称
        String os = System.getProperty("os.name");
        os = os.toUpperCase();
        if (os.startsWith("LINUX")) {
            return getSerialNumber("dmidecode |grep 'Serial Number'", "Serial Number", ":");
        } else if (os.startsWith("WINDOWS")) {
            String execResult = executeCmd("wmic BaseBoard get Product");
            String[] infos = execResult.split("\n");
            if (null != infos && infos.length >= 1) {
                return infos[1].trim();
            }
        }
        return null;
    }

    /**
     * 获取当前系统完整主板序列号
     *
     * @return
     */
    public static String getFullBoardCode() {
        //获取操作系统名称
        String os = System.getProperty("os.name");
        os = os.toUpperCase();
        if (os.startsWith("LINUX")) {
            return executeCmd("dmidecode |grep 'Serial Number'");
        } else if (os.startsWith("WINDOWS")) {
            return executeCmd("wmic BaseBoard get Product");
        } else {
            return "";
        }
    }

    /**
     * 获取唯一硬件码
     *
     * @return 唯一硬件码
     */
    public static String getHardwareCode() {
        String fullBoardCode = CommonUtil.getFullBoardCode();
        String cpuCode = CommonUtil.getCurSystemCPU();
        return fullBoardCode + cpuCode;
    }

    public static String getTableNameByPiid(int piid) {
        String tableName = "";
        switch (piid) {
            case 65537:
                tableName = "e_archives_neigh_area";
                break;
            case 65538:
                tableName = "e_archives_building";
                break;
            case 65539:
                tableName = "e_archives_unit";
                break;
            case 65540:
                tableName = "e_archives_house";
                break;
            case 65541:
                tableName = "e_archives_position";
                break;
            case 15:
                tableName = "e_archives_device";
                break;
            case 65542:
                tableName = "e_archives_device_extend";
                break;
            case 65543:
                tableName = "e_archives_neigh_struct";
                break;
            case 65544:
                tableName = "e_intercom_transfer";
                break;
            case 65545:
                tableName = "e_relative_intercom_account_permission";
                break;
            case 65546:
                tableName = "e_relative_house_person";
                break;
            case 65547:
                tableName = "e_index_flow_data";
                break;
            case 65548:
                tableName = "e_person_info";
                break;
            case 65549:
                tableName = "e_relative_person_tag";
                break;
            case 65550:
                tableName = "e_parkinglot_car";
                break;
            case 65551:
                tableName = "e_relative_house_ipc";
                break;
            case 65552:
                tableName = "e_relative_person_device";
                break;
            case 65553:
                tableName = "e_archives_neigh_config";
                break;
            default:
                tableName = "";
                break;
        }
        return tableName;
    }

    /***
     * 重启Tomcat
     */
    public static void restartTomcat() {
        String os = System.getProperty("os.name");
        os = os.toUpperCase();
        if (os.startsWith("LINUX")) {
            CommonUtil.executeCmd("systemctl restart tomcat\n");
        } else if (os.startsWith("WINDOWS")) {
            System.out.println("请手动重启。。。");
        }
    }

    /**
     * 字符串数组转int数组
     *
     * @param strArr 字符数组
     * @param count  截取的长度
     * @return
     */
    public static int[] strArrayToIntArray(String[] strArr, int count) {
        int[] b = new int[count];
        for (int i = 0; i < count; i++) {
            b[i] = Integer.parseInt(strArr[i]);
        }

        return b;
    }

    /**
     * int数组转成String数组
     *
     * @param intArr
     * @return
     */
    public static String[] intArrayToStrArray(int[] intArr) {
        int len = intArr.length;
        String[] b = new String[len];
        for (int i = 0; i < len; i++) {
            b[i] = intArr[i] + "";
        }
        return b;
    }

    /**
     * 逗号隔开的字符串（数字）转成字符串数组并排序
     *
     * @param str
     * @return
     */
    public static String[] strToSortStrArray(String str) {
        String[] strArr = str.split(",");
        int[] intArrays = strArrayToIntArray(strArr, strArr.length);
        Arrays.sort(intArrays);
        String[] sortStrArr = intArrayToStrArray(intArrays);
        return sortStrArr;
    }

    /**
     * 卡号是否能转为Long型校验
     *
     * @param cardNo 卡号
     * @return true：可以  false：不可以
     */
    public static boolean validateCardNo(String cardNo) {
        boolean flag = true;
        try {
            Long.parseLong(cardNo);
        } catch (NumberFormatException e) {
            flag = false;
            LOGGER.error("卡号大于Long最大值，转换异常！", e);
        }
        return flag;
    }


    public static void main(String[] args) {
        String dnsInfo = "# Generated by NetworkManager\n" +
                "nameserver 114.114.114.114\n" +
                "nameserver 114.114.114.115\n" +
                "nameserver 114.114.114.116";
//        int startIndex = dnsInfo.indexOf(NetConstant.NAME_SERVER);
//        String dnsStr = dnsInfo.substring(startIndex + 10, dnsInfo.length()).trim();
        // DNS服务器
        Matcher dnsMc = Pattern.compile("\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}").matcher(dnsInfo);
        if (dnsMc.find()) {
            System.out.println(dnsMc.group());
        }
    }

    /**
     * 判断是否仅包含英文字母、数字和汉字
     *
     * @param str 字符串
     * @return true为是，false为否
     */
    public static boolean isLetterDigitOrChinese(String str) {
        String regex = "^[a-z0-9A-Z\u4e00-\u9fa5]+$";
        return str.matches(regex);
    }


    /**
     * 字节数组转16进制
     * @param bytes 需要转换的byte数组
     * @return  转换后的Hex字符串
     */
    public static String bytesToHex(byte[] bytes) {
        StringBuffer sb = new StringBuffer();
        for(int i = 0; i < bytes.length; i++) {
            String hex = Integer.toHexString(bytes[i] & 0xFF);
            if(hex.length() < 2){
                sb.append(0);
            }
            sb.append(hex);
        }
        return sb.toString();
    }

}
